<script setup>
import { onMounted, ref } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElTag,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { searchAllApi, addApi, queryInfoApi, updateApi, deleteApi } from '@/api/clazz'
import { searchAllApi as searchAllTearchersApi } from '@/api/emp'

// 表格数据
const clazzList = ref([])
// 查询条件
const searchClazz = ref({ name: '', begin: '', end: '', date: [] })
// 控制对话框显示
const dialogVisible = ref(false)
// 表单引用
const formRef = ref()
const dialogTitle = ref('')

// 表单数据
const formData = ref({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''
})

// 表单验证规则
// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称长度应在4到30个字符之间', trigger: 'blur' }
  ],
  room: [
    { required: true, message: '请填写班级教室', trigger: 'blur' },
    { min: 1, max: 20, message: '班级教室长度应在1到30个字符之间', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '请选择开课时间', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结课时间', trigger: 'change' }
  ],
  masterId: [
    { required: true, message: '请选择班主任', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ]
}

// 模拟班主任数据（职位为老师的员工）
const teachers = ref([])

// 模拟学科数据
const subjects = ref([
  //Java/前端/大数据/Python/GO/嵌入式
  { id: 1, name: 'Java' },
  { id: 2, name: '前端' },
  { id: 3, name: '大数据' },
  { id: 4, name: 'Python' },
  { id: 5, name: 'GO' },
  { id: 6, name: '嵌入式' }
])

// 监听时间范围
import { watch } from 'vue'
watch(() => searchClazz.value.date, (newVal, oldVal) => {
  if (newVal && newVal.length == 2) {
    searchClazz.value.begin = newVal[0];
    searchClazz.value.end = newVal[1];
  } else {
    searchClazz.value.begin = '';
    searchClazz.value.end = '';
  }
})

// 分页
const currentPage = ref(1); //页码
const pageSize = ref(10); //每页展示记录数
const total = ref(0); //总记录数
// 查询所有班级


const search = async () => {
  const result = await searchAllApi(searchClazz.value.name, searchClazz.value.begin,
    searchClazz.value.end, currentPage.value, pageSize.value);
  if (result.code) {
    clazzList.value = result.data.rows;
    total.value = result.data.total;
  }
}
// 查询所有老师
const queryAllTearchers = async () => {
  const result = await searchAllTearchersApi();
  if (result.code) {
    teachers.value = result.data;
  }
}
// 清空
const clear = () => {
  searchClazz.value = { name: '', begin: '', end: '', date: [] };
  search();
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
  search();
}

// 页码变化时触发
const handleCurrentChange = (val) => {
  search();
}

// 修改 handleEdit 函数
const handleEdit = async (id) => {
  const result = await queryInfoApi(id);
  if (result.code && result.data) {
    dialogVisible.value = true;
    dialogTitle.value = '修改班级';
    // 安全地赋值，确保所有字段都有默认值
    formData.value = {
      id: result.data.id || '',
      name: result.data.name || '',
      room: result.data.room || '',
      beginDate: result.data.beginDate || '',
      endDate: result.data.endDate || '',
      masterId: result.data.masterId || '',
      subject: result.data.subject || ''
    };
  } else {
    ElMessage.error('获取班级信息失败');
  }
}


// 删除操作
const handleDelete = async (id) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      '确定要删除该班级吗？此操作不可恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用删除API
    const result = await deleteApi(id);
    if (result.code) {
      ElMessage.success('删除成功');
      // 重新加载列表
      await search();
    } else {
      ElMessage.error(result.msg || '删除失败');
    }
  } catch (error) {
    // 用户取消删除或出现其他错误
    ElMessage.info('已取消删除');
  }
}

// 打开新增班级对话框
const openAddDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增班级';
  // 确保 formData.value 被正确初始化
  formData.value = {
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: '',
    subject: ''
  };
}
// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 重置 formData
  formData.value = {
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: '',
    subject: ''
  };
}
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保 formData.value 不为 undefined
        if (!formData.value) {
          ElMessage.error('表单数据异常');
          return;
        }
        
        let result;
        if (formData.value.id) {
          // 修改班级
          result = await updateApi(formData.value);
        } else {
          // 新增班级
          result = await addApi(formData.value);
        }
        
        if (result.code) {
          ElMessage.success('保存成功');
          handleClose();
          await search(); // 等待搜索完成
        } else {
          ElMessage.error(result.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存班级出错:', error);
        ElMessage.error('保存失败: ' + error.message);
      }
    } else {
      ElMessage.warning('请检查表单填写是否正确');
      return false;
    }
  });
}

// 钩子函数
onMounted(() => {
  search();
  queryAllTearchers();
})

</script>

<template>
  <div>
    <h3>班级管理</h3>
    <br>
    <!-- 搜索栏 -->
    <div class="container">
      <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="searchClazz.name" placeholder="请输入班级名称" />
        </el-form-item>

        <el-form-item label="结课时间">
          <el-date-picker v-model="searchClazz.date" type="daterange" range-separator="到" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" @click="openAddDialog">新增班级</el-button>
    <br><br>

    <el-table :data="clazzList" border style="width: 100%">
      <!-- 序号列 -->
      <el-table-column type="index" label="序号" width="60" align="center" />

      <!-- 班级名称列 -->
      <el-table-column prop="name" label="班级名称" />

      <!-- 班级教室列 -->
      <el-table-column prop="room" label="班级教室" />

      <!-- 班主任列 -->
      <el-table-column prop="masterName" label="班主任" />

      <!-- 开课时间列 -->
      <el-table-column prop="beginDate" label="开课时间" width="120" />

      <!-- 结课时间列 -->
      <el-table-column prop="endDate" label="结课时间" width="120" />

      <!-- 状态列 -->
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已开班' ? 'success' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 最后操作时间列 -->
      <el-table-column prop="updateTime" label="最后操作时间" width="120">
        <template #default="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row.id)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <br>
    <!-- 分页条 -->
    <div class="container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50, 75, 100]" :background="background"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 新增班级对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleClose">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <!-- 班级名称 -->
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入班级名称，如：西安黑马JavaEE就业100期" />
        </el-form-item>

        <!-- 班级教室 -->
        <el-form-item label="班级教室" prop="room">
          <el-input v-model="formData.room" placeholder="请填写班级教室" />
        </el-form-item>

        <!-- 开课时间 -->
        <el-form-item label="开课时间" prop="beginDate">
          <el-date-picker v-model="formData.beginDate" type="date" placeholder="请选择开课时间" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>

        <!-- 结课时间 -->
        <el-form-item label="结课时间" prop="endDate">
          <el-date-picker v-model="formData.endDate" type="date" placeholder="请选择结课时间" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>

        <!-- 班主任 -->
        <el-form-item label="班主任" prop="masterId">
          <el-select v-model="formData.masterId" placeholder="请选择" style="width: 100%">
            <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
          </el-select>
        </el-form-item>

        <!-- 学科 -->
        <el-form-item label="学科" prop="subject">
          <el-select v-model="formData.subject" placeholder="请选择" style="width: 100%">
            <el-option v-for="subject in subjects" :key="subject.id" :label="subject.name" :value="subject.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
/* 可以添加额外的样式 */
</style>